/**
 * AI分析任务管理器
 * 负责分析任务的创建、执行、监控和管理
 */
class AnalysisManager {
    constructor() {
        this.tasks = [];
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalTasks = 0;
        this.filters = {
            status: '',
            task_type: '',
            execution_type: '',
            search: ''
        };
        this.stats = {
            total: 0,
            completed: 0,
            running: 0,
            failed: 0
        };
        this.refreshInterval = null;
        this.currentTaskId = null;
        this.isInitialized = false;
        
        // 新增：请求控制和状态跟踪
        this.isAutoRefreshEnabled = true;
        this.lastRequestTime = 0;
        this.requestCount = 0;
        this.errorCount = 0;
        this.maxErrors = 5;
        this.refreshIntervalTime = 15000; // 15秒刷新间隔
        this.minRequestInterval = 2000; // 最小请求间隔2秒
        this.debounceTimer = null;
        
        this.init();
    }

    /**
     * 初始化管理器
     */
    init() {
        if (this.isInitialized) {
            console.log('分析任务管理器已经初始化，跳过重复初始化');
            return;
        }

        console.log('分析任务管理器初始化...');
        this.bindEvents();

        // 初始化UI状态
        this.updateRefreshStatusUI();

        // 不在构造函数中立即加载数据，等待外部调用
        console.log('分析任务管理器初始化完成，等待数据加载指令...');

        this.isInitialized = true;
    }

    /**
     * 延迟加载 - 确保所有依赖就绪后调用
     */
    async delayedInit() {
        console.log('开始延迟初始化分析任务管理器...');

        // 检查必要依赖
        if (typeof ApiService === 'undefined' || !ApiService._isReady) {
            console.error('ApiService未就绪，延迟加载失败');
            return false;
        }

        if (typeof ErrorHandler === 'undefined' || !ErrorHandler._isReady) {
            console.error('ErrorHandler未就绪，延迟加载失败');
            return false;
        }

        try {
            this.loadTasks(); // 这会自动调用loadStats
            this.loadDatasources();

            // 启动自动刷新
            this.startAutoRefresh();

            console.log('分析任务管理器延迟初始化完成');
            return true;
        } catch (error) {
            console.error('分析任务管理器延迟初始化失败:', error);
            return false;
        }
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 模态框外部点击关闭
        document.addEventListener('click', (e) => {
            this.handleModalClick(e);
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeAllModals();
            }
        });
    }

    /**
     * 加载任务列表
     */
    async loadTasks() {
        try {
            // 检查必要的依赖
            if (typeof ApiService === 'undefined') {
                console.error('ApiService未加载，请检查JavaScript加载顺序');
                this.renderEmptyState('系统组件未加载完成，请刷新页面');
                return;
            }

            // 检查用户是否已登录
            if (typeof window.authManager !== 'undefined' && !window.authManager.isLoggedIn()) {
                console.log('用户未登录，跳过加载任务列表');
                this.renderEmptyState('请先登录以查看分析任务');
                return;
            }
            
            this.showLoading();
            
            // 过滤掉空值的过滤器参数
            const filteredFilters = Object.fromEntries(
                Object.entries(this.filters).filter(([_, value]) => value !== '' && value !== null && value !== undefined)
            );
            
            const response = await ApiService.getAnalysisTasks({
                page: this.currentPage,
                page_size: this.pageSize,
                ...filteredFilters
            });
            
            if (response.success) {
                console.log('API响应成功，数据:', response.data);
                // 验证响应数据结构
                if (response.data && typeof response.data === 'object') {
                    // 处理不同的响应格式
                    const items = Array.isArray(response.data.items) ? response.data.items :
                               Array.isArray(response.data) ? response.data : [];
                    const total = typeof response.data.total === 'number' ? response.data.total : items.length;

                    this.tasks = items;
                    this.totalTasks = total;
                    this.renderTasks();
                    this.renderPagination();
                    // 成功加载任务后，自动加载统计
                    this.loadStats();
                    // 处理请求成功
                    this.handleRequestSuccess();
                } else {
                    console.error('API响应数据格式错误:', response.data);
                    this.tasks = [];
                    this.totalTasks = 0;
                    this.renderTasks();
                    this.renderPagination();
                    this.showError('响应数据格式错误');
                }
            } else {
                console.error('API响应失败:', response);
                ErrorHandler.handleApiError(new Error(response.message || '未知错误'), 'load_tasks');
                // 处理请求错误
                this.handleRequestError();
            }
        } catch (error) {
            // 如果是401错误，说明用户未登录，这是正常的
            if (error.message && (error.message.includes('401') || error.message.includes('Not authenticated'))) {
                console.log('用户未登录，无法加载任务列表');
                this.renderEmptyState('请先登录以查看分析任务');
                return;
            }
            ErrorHandler.handleApiError(error, 'load_tasks');
            // 处理请求错误
            this.handleRequestError();
        } finally {
            this.hideLoading();
        }
    }

    /**
     * 加载任务统计
     */
    async loadStats() {
        try {
            // 检查用户是否已登录
            if (typeof window.authManager !== 'undefined' && !window.authManager.isLoggedIn()) {
                console.log('用户未登录，跳过加载任务统计');
                // 设置默认统计值
                this.stats = {
                    total_tasks: 0,
                    pending_tasks: 0,
                    running_tasks: 0,
                    completed_tasks: 0,
                    failed_tasks: 0,
                    today_tasks: 0
                };
                this.renderStats();
                return;
            }
            
            const response = await ApiService.getAnalysisTaskStats();
            
            if (response.success) {
                this.stats = response.data;
                this.renderStats();
                this.handleRequestSuccess();
            } else {
                this.handleRequestError();
            }
        } catch (error) {
            // 如果是401错误，说明用户未登录，这是正常的
            if (error.message && (error.message.includes('401') || error.message.includes('Not authenticated'))) {
                console.log('用户未登录，无法加载任务统计');
                // 设置默认统计值
                this.stats = {
                    total_tasks: 0,
                    pending_tasks: 0,
                    running_tasks: 0,
                    completed_tasks: 0,
                    failed_tasks: 0,
                    today_tasks: 0
                };
                this.renderStats();
                return;
            }
            console.warn('加载任务统计失败:', error);
            this.handleRequestError();
        }
    }

    /**
     * 加载数据源列表
     */
    async loadDatasources() {
        // 检查用户是否已登录
        if (typeof window.authManager !== 'undefined' && !window.authManager.isLoggedIn()) {
            console.log('用户未登录，跳过加载数据源');
            return;
        }
        
        // 显示加载状态
        this.showDatasourceLoading();
        
        try {
            console.log('开始加载数据源列表...');
            const response = await ApiService.getDataSources();
            
            if (response.success) {
                console.log('数据源加载成功:', response.data);
                // 处理不同的响应格式
                let datasources = [];
                if (Array.isArray(response.data)) {
                    // 如果直接返回数组
                    datasources = response.data;
                } else if (response.data.datasources) {
                    // 如果返回包含datasources字段的对象
                    datasources = response.data.datasources;
                } else if (response.data.items) {
                    // 如果返回包含items字段的对象
                    datasources = response.data.items;
                }
                
                console.log('处理后的数据源列表:', datasources);
                this.renderDatasourceOptions(datasources);
                
                // 显示成功消息
                if (datasources && datasources.length > 0) {
                    if (typeof NotificationService !== 'undefined') {
                        NotificationService.success(`成功加载 ${datasources.length} 个数据源`);
                    }
                }
            } else {
                console.error('数据源加载失败:', response.message);
                // 尝试使用分析任务专用的数据源接口
                await this.loadAnalysisTaskDatasources();
            }
        } catch (error) {
            // 如果是401错误，说明用户未登录，这是正常的
            if (error.message && (error.message.includes('401') || error.message.includes('Not authenticated'))) {
                console.log('用户未登录，无法加载数据源');
                this.hideDatasourceLoading();
                return;
            }
            console.warn('通用数据源接口加载失败，尝试专用接口:', error);
            // 尝试使用分析任务专用的数据源接口
            await this.loadAnalysisTaskDatasources();
        }
    }

    /**
     * 加载分析任务专用的数据源列表
     */
    async loadAnalysisTaskDatasources() {
        try {
            console.log('尝试加载分析任务专用数据源列表...');
            const response = await ApiService.getAnalysisTaskDatasources();
            
            if (response.success) {
                console.log('分析任务数据源加载成功:', response.data);
                let datasources = [];
                if (Array.isArray(response.data)) {
                    datasources = response.data;
                } else if (response.data.datasources) {
                    datasources = response.data.datasources;
                } else if (response.data.items) {
                    datasources = response.data.items;
                }
                
                console.log('处理后的分析任务数据源列表:', datasources);
                this.renderDatasourceOptions(datasources);
                
                // 显示成功消息
                if (datasources && datasources.length > 0) {
                    if (typeof NotificationService !== 'undefined') {
                        NotificationService.success(`成功加载 ${datasources.length} 个数据源`);
                    }
                }
            } else {
                console.error('分析任务数据源加载失败:', response.message);
                this.showDatasourceError('加载数据源失败，请检查权限设置');
            }
        } catch (error) {
            console.error('分析任务数据源加载异常:', error);
            this.showDatasourceError('网络错误，请稍后重试');
        }
    }

    /**
     * 显示数据源加载错误
     */
    showDatasourceError(message) {
        const select = document.getElementById('taskDataSource');
        if (select) {
            select.innerHTML = '<option value="">加载数据源失败</option>';
            select.disabled = true;
        }
        
        // 隐藏加载状态
        this.hideDatasourceLoading();
        
        // 显示错误提示
        if (typeof NotificationService !== 'undefined') {
            NotificationService.error(message);
        } else {
            console.error('数据源加载错误:', message);
        }
    }

    /**
     * 显示数据源加载状态
     */
    showDatasourceLoading() {
        const select = document.getElementById('taskDataSource');
        if (select) {
            select.innerHTML = '<option value="">正在加载数据源...</option>';
            select.disabled = true;
        }
        
        // 添加加载图标
        const loadingIcon = document.getElementById('datasourceLoadingIcon');
        if (loadingIcon) {
            loadingIcon.classList.remove('hidden');
        }
    }

    /**
     * 隐藏数据源加载状态
     */
    hideDatasourceLoading() {
        const loadingIcon = document.getElementById('datasourceLoadingIcon');
        if (loadingIcon) {
            loadingIcon.classList.add('hidden');
        }
    }

    /**
     * 渲染空状态
     */
    renderEmptyState(message) {
        const tbody = document.getElementById('taskTableBody');
        const emptyState = document.getElementById('tasksEmptyState');
        
        if (tbody) {
            tbody.innerHTML = '';
        }
        
        if (emptyState) {
            emptyState.innerHTML = `
                <div class="text-center py-12">
                    <i class="fas fa-lock text-4xl text-slate-300 mb-4"></i>
                    <p class="text-slate-500 text-lg">${message}</p>
                    <button onclick="window.location.href='/web/login'" class="mt-4 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                        前往登录
                    </button>
                </div>
            `;
            emptyState.classList.remove('hidden');
        }
    }

    /**
     * 渲染任务统计
     */
    renderStats() {
        // 安全地获取统计数据，设置默认值
        const elements = {
            'totalTasksCount': typeof this.stats.total_tasks === 'number' ? this.stats.total_tasks : 0,
            'pendingTasksCount': typeof this.stats.pending_tasks === 'number' ? this.stats.pending_tasks : 0,
            'completedTasksCount': typeof this.stats.completed_tasks === 'number' ? this.stats.completed_tasks : 0,
            'runningTasksCount': typeof this.stats.running_tasks === 'number' ? this.stats.running_tasks : 0,
            'failedTasksCount': typeof this.stats.failed_tasks === 'number' ? this.stats.failed_tasks : 0
        };

        console.log('渲染统计数据:', this.stats);

        Object.entries(elements).forEach(([id, value]) => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = value.toLocaleString();
            }
        });
    }

    /**
     * 渲染任务列表
     */
    renderTasks() {
        console.log('开始渲染任务列表，任务数量:', this.tasks.length);
        const tbody = document.getElementById('taskTableBody');
        const emptyState = document.getElementById('tasksEmptyState');
        const pagination = document.getElementById('tasksPagination');

        if (!tbody) {
            console.error('找不到taskTableBody元素');
            return;
        }

        if (this.tasks.length === 0) {
            console.log('任务列表为空，显示空状态');
            tbody.innerHTML = '';
            emptyState.classList.remove('hidden');
            pagination.classList.add('hidden');
            return;
        }

        console.log('渲染任务列表，隐藏空状态');
        emptyState.classList.add('hidden');
        pagination.classList.remove('hidden');

        const rows = this.tasks.map(task => this.createTaskRow(task)).join('');
        console.log('生成的HTML行数:', rows.split('</tr>').length - 1);
        tbody.innerHTML = rows;
    }

    /**
     * 创建任务行HTML
     */
    createTaskRow(task) {
        const statusInfo = this.getStatusInfo(task.status);
        const taskTypeInfo = this.getTypeInfo(task.task_type);
        const executionTypeInfo = this.getExecutionTypeInfo(task.execution_type);

        return `
            <tr class="hover:bg-slate-50">
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="w-8 h-8 bg-indigo-100 rounded-lg flex items-center justify-center mr-3">
                            <i class="fas fa-brain text-indigo-600 text-sm"></i>
                        </div>
                        <div>
                            <div class="text-sm font-medium text-slate-900">${task.name}</div>
                            <div class="text-sm text-slate-500">${task.description || '无描述'}</div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="text-sm text-slate-900">${taskTypeInfo.name}</div>
                    <div class="text-sm text-slate-500">${executionTypeInfo.name}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs rounded-full ${statusInfo.class}">
                        ${statusInfo.text}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="w-full">
                        <div class="flex items-center justify-between mb-1">
                            <span class="text-sm text-slate-600">${task.progress.toFixed(1)}%</span>
                            <span class="text-xs text-slate-500">${this.formatDuration(task.duration)}</span>
                        </div>
                        <div class="w-full bg-slate-200 rounded-full h-2">
                            <div class="bg-indigo-600 h-2 rounded-full transition-all duration-300" 
                                 style="width: ${task.progress}%"></div>
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-900">
                    <div>总数: ${task.total_count}</div>
                    <div class="text-green-600">成功: ${task.success_count}</div>
                    <div class="text-red-600">失败: ${task.failed_count}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                    ${this.formatDate(task.created_at)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex space-x-2">
                        <button onclick="analysisManager.showTaskDetail(${task.id})" 
                                class="text-indigo-600 hover:text-indigo-900" title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${this.getTaskActionButtons(task)}
                    </div>
                </td>
            </tr>
        `;
    }

    /**
     * 获取任务操作按钮
     */
    getTaskActionButtons(task) {
        let buttons = '';

        switch (task.status) {
            case 'pending':
                buttons += `
                    <button onclick="analysisManager.startTask(${task.id})" 
                            class="text-green-600 hover:text-green-900" title="启动">
                        <i class="fas fa-play"></i>
                    </button>
                `;
                buttons += `
                    <button onclick="analysisManager.editTask(${task.id})" 
                            class="text-blue-600 hover:text-blue-900" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                `;
                break;
            case 'running':
                buttons += `
                    <button onclick="analysisManager.stopTask(${task.id})" 
                            class="text-red-600 hover:text-red-900" title="停止">
                        <i class="fas fa-stop"></i>
                    </button>
                `;
                break;
            case 'failed':
                if (task.can_retry) {
                    buttons += `
                        <button onclick="analysisManager.retryTask(${task.id})" 
                                class="text-yellow-600 hover:text-yellow-900" title="重试">
                            <i class="fas fa-redo"></i>
                        </button>
                    `;
                }
                break;
        }

        buttons += `
            <button onclick="analysisManager.deleteTask(${task.id})" 
                    class="text-red-600 hover:text-red-900" title="删除">
                <i class="fas fa-trash"></i>
            </button>
        `;

        return buttons;
    }

    /**
     * 获取状态信息
     */
    getStatusInfo(status) {
        const statusMap = {
            'pending': { text: '待执行', class: 'bg-yellow-100 text-yellow-800' },
            'running': { text: '进行中', class: 'bg-blue-100 text-blue-800' },
            'completed': { text: '已完成', class: 'bg-green-100 text-green-800' },
            'failed': { text: '失败', class: 'bg-red-100 text-red-800' },
            'cancelled': { text: '已取消', class: 'bg-gray-100 text-gray-800' },
            'timeout': { text: '超时', class: 'bg-orange-100 text-orange-800' }
        };
        return statusMap[status] || { text: status, class: 'bg-gray-100 text-gray-800' };
    }

    /**
     * 获取任务类型信息
     */
    getTypeInfo(type) {
        const typeMap = {
            'RegionalAnalysis': { name: '区域分析' },
            'ComplaintTypeAnalysis': { name: '信访类型分析' },
            'SentimentAnalysis': { name: '情感分析' },
            'ComplianceAnalysis': { name: '规范性分析' },
            'DuplicateAnalysis': { name: '重复信访分析' }
        };
        
        // 处理多选任务类型（逗号分隔）
        if (!type) return { name: '未设置' };
        
        const types = type.split(',').filter(t => t.trim());
        if (types.length === 1) {
            return typeMap[types[0]] || { name: types[0] };
        } else if (types.length > 1) {
            const names = types.map(t => typeMap[t]?.name || t).join('、');
            return { name: names, isMultiple: true };
        }
        
        return { name: type };
    }

    /**
     * 获取执行类型信息
     */
    getExecutionTypeInfo(type) {
        const typeMap = {
            'single_analysis': { name: '单次分析' },
            'batch_analysis': { name: '批量分析' }
        };
        return typeMap[type] || { name: type };
    }

    /**
     * 获取服务状态样式类
     */
    getServiceStatusClass(status) {
        const statusMap = {
            'pending': 'bg-yellow-100 text-yellow-800',
            'running': 'bg-blue-100 text-blue-800',
            'completed': 'bg-green-100 text-green-800',
            'failed': 'bg-red-100 text-red-800',
            'cancelled': 'bg-gray-100 text-gray-800',
            'timeout': 'bg-orange-100 text-orange-800'
        };
        return statusMap[status] || 'bg-gray-100 text-gray-800';
    }

    /**
     * 获取服务状态文本
     */
    getServiceStatusText(status) {
        const statusMap = {
            'pending': '待执行',
            'running': '进行中',
            'completed': '已完成',
            'failed': '失败',
            'cancelled': '已取消',
            'timeout': '超时'
        };
        return statusMap[status] || status;
    }

    /**
     * 获取配置键标签
     */
    getConfigKeyLabel(key) {
        const labelMap = {
            'timeout': '超时时间',
            'priority': '优先级',
            'max_retries': '最大重试次数',
            'batch_size': '批次大小',
            'concurrency': '并发数',
            'retry_count': '重试次数',
            'retry_delay': '重试延迟',
            'task_timeout': '任务超时',
            'service_timeout': '服务超时'
        };
        return labelMap[key] || key;
    }

    /**
     * 格式化配置值
     */
    formatConfigValue(key, value) {
        if (value === null || value === undefined) return '-';
        
        switch (key) {
            case 'timeout':
            case 'max_retries':
            case 'batch_size':
            case 'concurrency':
            case 'retry_count':
            case 'retry_delay':
            case 'task_timeout':
            case 'service_timeout':
                return typeof value === 'number' ? value.toString() : value;
            
            case 'priority':
                const priorityMap = {
                    'low': '低',
                    'medium': '中',
                    'high': '高',
                    'urgent': '紧急'
                };
                return priorityMap[value] || value;
            
            default:
                return typeof value === 'object' ? JSON.stringify(value) : value.toString();
        }
    }

    /**
     * 渲染分页
     */
    renderPagination() {
        const container = document.getElementById('paginationContainer');
        const pageStart = document.getElementById('pageStart');
        const pageEnd = document.getElementById('pageEnd');
        const totalItems = document.getElementById('totalItems');

        if (!container) return;

        const totalPages = Math.ceil(this.totalTasks / this.pageSize);
        const start = (this.currentPage - 1) * this.pageSize + 1;
        const end = Math.min(this.currentPage * this.pageSize, this.totalTasks);

        if (pageStart) pageStart.textContent = this.totalTasks > 0 ? start : 0;
        if (pageEnd) pageEnd.textContent = end;
        if (totalItems) totalItems.textContent = this.totalTasks;

        let paginationHTML = '';

        // 上一页按钮
        paginationHTML += `
            <button onclick="analysisManager.goToPage(${this.currentPage - 1})" 
                    ${this.currentPage === 1 ? 'disabled' : ''}>
                <i class="fas fa-chevron-left"></i>
            </button>
        `;

        // 页码按钮
        for (let i = Math.max(1, this.currentPage - 2); i <= Math.min(totalPages, this.currentPage + 2); i++) {
            paginationHTML += `
                <button onclick="analysisManager.goToPage(${i})" 
                        ${i === this.currentPage ? 'class="active"' : ''}>
                    ${i}
                </button>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <button onclick="analysisManager.goToPage(${this.currentPage + 1})" 
                    ${this.currentPage === totalPages ? 'disabled' : ''}>
                <i class="fas fa-chevron-right"></i>
            </button>
        `;

        container.innerHTML = paginationHTML;
    }

    /**
     * 渲染数据源选项
     */
    renderDatasourceOptions(datasources) {
        const select = document.getElementById('taskDataSource');
        if (!select) {
            console.warn('未找到数据源下拉框元素: taskDataSource');
            return;
        }

        console.log('开始渲染数据源选项，数据源数量:', datasources?.length || 0);

        // 隐藏加载状态
        this.hideDatasourceLoading();

        // 清空现有选项，保留第一个选项（通常是"请选择数据源"）
        while (select.children.length > 1) {
            select.removeChild(select.lastChild);
        }

        // 检查数据源数组
        if (!datasources || !Array.isArray(datasources) || datasources.length === 0) {
            console.log('没有可用的数据源');
            const option = document.createElement('option');
            option.value = "";
            option.textContent = "暂无可用数据源";
            option.disabled = true;
            select.appendChild(option);
            select.disabled = true;
            return;
        }

        // 启用下拉框
        select.disabled = false;

        // 添加数据源选项
        let hasValidOptions = false;
        let activeCount = 0;
        datasources.forEach((ds, index) => {
            console.log(`处理数据源 ${index + 1}:`, ds);
            
            // 验证数据源对象
            if (!ds || !ds.id || !ds.name) {
                console.warn('跳过无效数据源:', ds);
                return;
            }

            const option = document.createElement('option');
            option.value = ds.id;
            
            // 构建显示文本，包含更多有用信息
            let displayText = ds.name;
            
            // 添加类型信息
            if (ds.type) {
                const typeMap = {
                    'database': '数据库',
                    'excel': 'Excel文件',
                    'csv': 'CSV文件',
                    'api': 'API接口'
                };
                const typeText = typeMap[ds.type] || ds.type;
                displayText += ` (${typeText})`;
            }
            
            // 添加状态信息
            if (ds.status) {
                const statusMap = {
                    'active': '已连接',
                    'inactive': '未连接',
                    'error': '连接错误',
                    'testing': '测试中'
                };
                const statusText = statusMap[ds.status] || ds.status;
                displayText += ` - ${statusText}`;
                
                if (ds.status === 'active') {
                    activeCount++;
                }
            }
            
            // 添加记录数信息（如果有）
            if (ds.record_count !== undefined && ds.record_count > 0) {
                displayText += ` [${ds.record_count}条记录]`;
            }
            
            option.textContent = displayText;
            
            // 如果数据源状态不是active，禁用该选项
            if (ds.status !== 'active') {
                option.disabled = true;
                option.textContent += ' (不可用)';
            }
            
            select.appendChild(option);
            hasValidOptions = true;
        });

        console.log(`数据源选项渲染完成，有效选项数量: ${hasValidOptions ? datasources.length : 0}, 活跃数据源: ${activeCount}`);

        // 如果没有有效的数据源选项，添加提示
        if (!hasValidOptions) {
            const option = document.createElement('option');
            option.value = "";
            option.textContent = "暂无可用数据源";
            option.disabled = true;
            select.appendChild(option);
            select.disabled = true;
        }

        // 如果有数据源但没有活跃的，显示提示
        if (hasValidOptions && activeCount === 0) {
            if (typeof NotificationService !== 'undefined') {
                NotificationService.warning('没有可用的数据源，请检查数据源连接状态');
            }
        }
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const loadingState = document.getElementById('tasksLoadingState');
        if (loadingState) {
            loadingState.classList.remove('hidden');
        }
    }

    /**
     * 隐藏加载状态
     */
    hideLoading() {
        const loadingState = document.getElementById('tasksLoadingState');
        if (loadingState) {
            loadingState.classList.add('hidden');
        }
    }

    /**
     * 刷新任务列表
     */
    refreshTasks() {
        console.log('刷新任务列表...');
        // 重置分页到第一页
        this.currentPage = 1;
        this.loadTasks();
    }

    /**
     * 应用筛选器
     */
    applyFilters() {
        this.filters.status = document.getElementById('taskStatusFilter').value;
        this.filters.task_type = document.getElementById('taskTypeFilter').value;
        this.filters.execution_type = document.getElementById('executionTypeFilter').value;
        this.filters.search = document.getElementById('taskSearchInput').value;
        this.currentPage = 1;
        console.log('应用筛选器，当前筛选条件:', this.filters);
        this.loadTasks();
    }

    /**
     * 跳转到指定页
     */
    goToPage(page) {
        const totalPages = Math.ceil(this.totalTasks / this.pageSize);
        if (page >= 1 && page <= totalPages) {
            this.currentPage = page;
            this.loadTasks();
        }
    }

    /**
     * 显示新建任务模态框
     */
    showAddTaskModal() {
        const modal = document.getElementById('addAnalysisModal');
        if (modal) {
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            this.resetTaskForm();
        }
    }

    /**
     * 关闭新建任务模态框
     */
    closeAddTaskModal() {
        const modal = document.getElementById('addAnalysisModal');
        if (modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            this.resetTaskForm();
        }
    }

    /**
     * 重置任务表单
     */
    resetTaskForm() {
        document.getElementById('addTaskForm').reset();
        
        // 重置服务配置
        const servicesContainer = document.getElementById('servicesContainer');
        if (servicesContainer) {
            // 保留第一个服务配置，移除其他的
            while (servicesContainer.children.length > 1) {
                servicesContainer.removeChild(servicesContainer.lastChild);
            }
        }
    }

    /**
     * 保存任务
     */
    async saveTask() {
        try {
            const saveBtn = document.getElementById('saveTaskBtn');
            if (!saveBtn) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('保存按钮未找到');
                }
                console.error('saveTask: saveTaskBtn element not found');
                return;
            }
            
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>创建中...';
            saveBtn.disabled = true;

            const taskData = this.collectTaskData();
            
            if (!taskData) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('表单数据不完整，请检查输入');
                }
                return;
            }
            
            const response = await ApiService.createAnalysisTask(taskData);
            
            if (response.success) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.success('任务创建成功');
                }
                this.closeAddTaskModal();
                this.refreshTasks();
            } else {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error(response.message || '创建任务失败');
                }
            }
        } catch (error) {
            console.error('saveTask error:', error);
            if (typeof ErrorHandler !== 'undefined') {
                ErrorHandler.handleApiError(error, 'save_task');
            } else if (typeof NotificationService !== 'undefined') {
                NotificationService.error('创建任务时发生错误');
            }
        } finally {
            const saveBtn = document.getElementById('saveTaskBtn');
            if (saveBtn) {
                saveBtn.innerHTML = '<i class="fas fa-save mr-2"></i>创建任务';
                saveBtn.disabled = false;
            }
        }
    }

    /**
     * 收集任务表单数据
     */
    collectTaskData() {
        try {
            // 表单验证
            const taskNameInput = document.getElementById('taskName');
            if (!taskNameInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('任务名称输入框未找到');
                }
                console.error('collectTaskData: taskName element not found');
                return null;
            }
            
            const taskName = taskNameInput.value.trim();
            if (!taskName) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请输入任务名称');
                }
                return null;
            }

            // 验证至少选择一个任务类型
            const taskTypes = [];
            const taskTypeCheckboxes = document.querySelectorAll('.task-type-checkbox:checked');
            if (taskTypeCheckboxes.length === 0) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请至少选择一个任务类型');
                }
                return null;
            }
            
            taskTypeCheckboxes.forEach(checkbox => {
                taskTypes.push(checkbox.value);
            });
            
            const taskTypeString = taskTypes.join(',');

            // 验证数据源
            const dataSourceInput = document.getElementById('taskDataSource');
            if (!dataSourceInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('数据源选择框未找到');
                }
                console.error('collectTaskData: taskDataSource element not found');
                return null;
            }
            
            const dataSourceId = dataSourceInput.value;
            if (!dataSourceId) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请选择数据源');
                }
                return null;
            }

            // 验证分析时段（如果提供了结束日期，则开始日期必须存在）
            const analysisStartDateInput = document.getElementById('analysisStartDate');
            const analysisEndDateInput = document.getElementById('analysisEndDate');
            
            if (!analysisStartDateInput || !analysisEndDateInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('分析时段输入框未找到');
                }
                console.error('collectTaskData: analysis date elements not found');
                return null;
            }
            
            const analysisStartDate = analysisStartDateInput.value;
            const analysisEndDate = analysisEndDateInput.value;
            
            if (analysisEndDate && !analysisStartDate) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请选择分析开始日期');
                }
                return null;
            }

            // 获取其他必填字段
            const executionTypeInput = document.getElementById('executionType');
            const maxRetriesInput = document.getElementById('maxRetries');
            
            if (!executionTypeInput || !maxRetriesInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('执行方式或重试次数输入框未找到');
                }
                console.error('collectTaskData: executionType or maxRetries element not found');
                return null;
            }

            return {
                name: taskName,
                task_type: taskTypeString,
                execution_type: executionTypeInput.value,
                data_source_id: parseInt(dataSourceId),
                analysis_start_date: analysisStartDate || null,
                analysis_end_date: analysisEndDate || null,
                services: [], // 移除服务配置
                max_retries: parseInt(maxRetriesInput.value) || 3,
                priority: 'medium', // 添加默认优先级
                config: {} // 简化配置
            };
        } catch (error) {
            console.error('collectTaskData error:', error);
            if (typeof NotificationService !== 'undefined') {
                NotificationService.error('收集表单数据时发生错误');
            }
            return null;
        }
    }

    /**
     * 添加服务配置
     */
    addServiceConfig() {
        const container = document.getElementById('servicesContainer');
        if (!container) return;

        const serviceId = Date.now();
        const serviceHtml = `
            <div class="service-config border border-slate-200 rounded-lg p-4" data-service-id="${serviceId}">
                <div class="flex justify-between items-start mb-3">
                    <h4 class="font-medium text-slate-800">新服务配置</h4>
                    <div class="flex items-center space-x-2">
                        <div class="flex items-center">
                            <input type="checkbox" class="service-enable mr-2" checked>
                            <label class="text-sm text-slate-600">启用</label>
                        </div>
                        <button type="button" onclick="analysisManager.removeServiceConfig(${serviceId})" 
                                class="text-red-600 hover:text-red-800">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务名称</label>
                        <input type="text" class="service-name w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="新服务" placeholder="请输入服务名称">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务类型</label>
                        <select class="service-type w-full px-3 py-1 text-sm border border-slate-300 rounded">
                            <option value="information_extraction">信息提取</option>
                            <option value="pollution_type_recognition">污染类型识别</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">批次大小</label>
                        <input type="number" class="batch-size w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="10" min="1" max="100">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">并发数</label>
                        <input type="number" class="concurrency w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="5" min="1" max="20">
                    </div>
                </div>
            </div>
        `;

        container.insertAdjacentHTML('beforeend', serviceHtml);
    }

    /**
     * 移除服务配置
     */
    removeServiceConfig(serviceId) {
        const serviceConfig = document.querySelector(`[data-service-id="${serviceId}"]`);
        if (serviceConfig) {
            serviceConfig.remove();
        }
    }

    /**
     * 显示任务详情
     */
    async showTaskDetail(taskId) {
        this.currentTaskId = taskId;
        
        try {
            console.log('获取任务详情，任务ID:', taskId);
            const response = await ApiService.getAnalysisTask(taskId);
            console.log('任务详情API响应:', response);
            console.log('response.success:', response.success);
            console.log('response类型:', typeof response);
            
            if (response.success) {
                console.log('任务详情数据:', response.data);
                this.renderTaskDetail(response.data);
                
                const modal = document.getElementById('taskDetailModal');
                if (modal) {
                    modal.classList.remove('hidden');
                    modal.classList.add('flex');
                }
            } else {
                console.error('获取任务详情失败:', response.message);
                NotificationService.error(response.message || '获取任务详情失败');
            }
        } catch (error) {
            console.error('获取任务详情异常:', error);
            ErrorHandler.handleApiError(error, 'get_task_detail');
        }
    }

    /**
     * 渲染任务详情
     */
    renderTaskDetail(taskData) {
        const container = document.getElementById('taskDetailContent');
        if (!container) return;

        // 安全检查：确保taskData和taskData.task存在
        if (!taskData || !taskData.task) {
            console.error('任务数据格式错误:', taskData);
            container.innerHTML = '<div class="text-red-600">任务数据加载失败</div>';
            return;
        }

        const statusInfo = this.getStatusInfo(taskData.task.status);
        const taskTypeInfo = this.getTypeInfo(taskData.task.task_type);
        const executionTypeInfo = this.getExecutionTypeInfo(taskData.task.execution_type);

        const html = `
            <div class="space-y-6">
                <!-- 基本信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="font-medium text-slate-800 mb-3">基本信息</h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <span class="text-sm text-slate-600">任务名称:</span>
                            <p class="font-medium">${this.escapeHtml(taskData.task.name || '')}</p>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">任务类型:</span>
                            <p class="font-medium">${taskTypeInfo.name || '未知'}</p>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">执行方式:</span>
                            <p class="font-medium">${executionTypeInfo.name || '未知'}</p>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">状态:</span>
                            <span class="px-2 py-1 text-xs rounded-full ${statusInfo.class}">
                                ${statusInfo.text}
                            </span>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">创建时间:</span>
                            <p class="font-medium">${this.formatDate(taskData.task.created_at)}</p>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">最后更新:</span>
                            <p class="font-medium">${this.formatDate(taskData.task.updated_at)}</p>
                        </div>
                    </div>
                    ${taskData.task.description ? `
                        <div class="mt-4">
                            <span class="text-sm text-slate-600">描述:</span>
                            <p class="font-medium">${this.escapeHtml(taskData.task.description)}</p>
                        </div>
                    ` : ''}
                    ${taskData.task.data_source_id ? `
                        <div class="mt-4">
                            <span class="text-sm text-slate-600">数据源ID:</span>
                            <p class="font-medium">${taskData.task.data_source_id}</p>
                        </div>
                    ` : ''}
                </div>

                <!-- 执行信息 -->
                <div class="bg-slate-50 rounded-lg p-4">
                    <h4 class="font-medium text-slate-800 mb-3">执行信息</h4>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <span class="text-sm text-slate-600">进度:</span>
                            <div class="mt-1">
                                <div class="flex items-center justify-between mb-1">
                                    <span class="text-sm font-medium">${(taskData.task.progress || 0).toFixed(1)}%</span>
                                    <span class="text-xs text-slate-500">${this.formatDuration(taskData.task.duration)}</span>
                                </div>
                                <div class="w-full bg-slate-200 rounded-full h-2">
                                    <div class="bg-indigo-600 h-2 rounded-full transition-all duration-300" 
                                         style="width: ${taskData.task.progress || 0}%"></div>
                                </div>
                            </div>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">执行统计:</span>
                            <div class="mt-1 space-y-1">
                                <div class="text-sm"><span class="text-green-600">成功:</span> ${taskData.task.success_count || 0}</div>
                                <div class="text-sm"><span class="text-red-600">失败:</span> ${taskData.task.failed_count || 0}</div>
                                <div class="text-sm"><span class="text-slate-600">总计:</span> ${taskData.task.total_count || 0}</div>
                            </div>
                        </div>
                        <div>
                            <span class="text-sm text-slate-600">时间信息:</span>
                            <div class="mt-1 space-y-1">
                                <div class="text-sm">开始: ${taskData.task.start_time ? this.formatDate(taskData.task.start_time) : '未开始'}</div>
                                <div class="text-sm">结束: ${taskData.task.end_time ? this.formatDate(taskData.task.end_time) : '进行中'}</div>
                                <div class="text-sm">重试: ${taskData.task.retry_count || 0}/${taskData.task.max_retries || 0}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 服务执行记录 -->
                ${taskData.services && Array.isArray(taskData.services) && taskData.services.length > 0 ? `
                    <div class="bg-slate-50 rounded-lg p-4">
                        <h4 class="font-medium text-slate-800 mb-3">服务执行记录</h4>
                        <div class="space-y-3">
                            ${taskData.services.map(service => `
                                <div class="bg-white rounded-lg p-3 border border-slate-200">
                                    <div class="flex justify-between items-start mb-2">
                                        <div>
                                            <h5 class="font-medium text-slate-800">${this.escapeHtml(service.name || service.service_name || '未知服务')}</h5>
                                            <p class="text-sm text-slate-600">类型: ${this.escapeHtml(service.type || service.service_type || '未知类型')}</p>
                                        </div>
                                        <span class="px-2 py-1 text-xs rounded-full ${this.getServiceStatusClass(service.status || 'completed')}">
                                            ${this.getServiceStatusText(service.status || 'completed')}
                                        </span>
                                    </div>
                                    <div class="grid grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                                        <div>输入: ${service.input_count || service.total_count || 0}</div>
                                        <div>输出: ${service.output_count || service.success_count || 0}</div>
                                        <div class="text-green-600">成功: ${service.success_count || 0}</div>
                                        <div class="text-red-600">失败: ${service.failed_count || 0}</div>
                                    </div>
                                    ${service.duration ? `
                                        <div class="mt-2 text-xs text-slate-500">
                                            执行时长: ${parseFloat(service.duration).toFixed(2)}秒
                                        </div>
                                    ` : ''}
                                    ${service.error_message ? `
                                        <div class="mt-2 text-xs text-red-600">
                                            错误: ${this.escapeHtml(service.error_message)}
                                        </div>
                                    ` : ''}
                                    ${service.parameters && Object.keys(service.parameters).length > 0 ? `
                                        <div class="mt-2 text-xs text-slate-500">
                                            参数: ${JSON.stringify(service.parameters)}
                                        </div>
                                    ` : ''}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : '<div class="bg-slate-50 rounded-lg p-4"><p class="text-slate-600">暂无服务执行记录</p></div>'}

                <!-- 错误信息 -->
                ${taskData.task.error_message ? `
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                        <h4 class="font-medium text-red-800 mb-2">错误信息</h4>
                        <p class="text-sm text-red-700">${this.escapeHtml(taskData.task.error_message)}</p>
                    </div>
                ` : ''}

                <!-- 配置信息 -->
                ${taskData.task.config && Object.keys(taskData.task.config).length > 0 ? `
                    <div class="bg-slate-50 rounded-lg p-4">
                        <h4 class="font-medium text-slate-800 mb-3">配置信息</h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
                            ${Object.entries(taskData.task.config).map(([key, value]) => `
                                <div>
                                    <span class="text-slate-600">${this.getConfigKeyLabel(key)}:</span>
                                    <span class="font-medium">${this.formatConfigValue(key, value)}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}

                <!-- 操作按钮 -->
                <div class="flex justify-end space-x-3 pt-4 border-t border-slate-200">
                    ${this.getTaskDetailActions(taskData.task)}
                </div>
            </div>
        `;

        container.innerHTML = html;
    }

    /**
     * 获取任务详情操作按钮
     */
    getTaskDetailActions(task) {
        let actions = '';

        switch (task.status) {
            case 'pending':
                actions = `
                    <button onclick="analysisManager.startTask(${task.id})" 
                            class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
                        <i class="fas fa-play mr-2"></i>启动任务
                    </button>
                `;
                break;
            case 'running':
                actions = `
                    <button onclick="analysisManager.stopTask(${task.id})" 
                            class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors">
                        <i class="fas fa-stop mr-2"></i>停止任务
                    </button>
                `;
                break;
            case 'failed':
                if (task.can_retry) {
                    actions = `
                        <button onclick="analysisManager.retryTask(${task.id})" 
                                class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition-colors">
                            <i class="fas fa-redo mr-2"></i>重试任务
                        </button>
                    `;
                }
                break;
        }

        return actions;
    }

    /**
     * 关闭任务详情模态框
     */
    closeTaskDetailModal() {
        const modal = document.getElementById('taskDetailModal');
        if (modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }
        this.currentTaskId = null;
    }

    /**
     * 刷新任务详情
     */
    async refreshTaskDetail() {
        if (this.currentTaskId) {
            await this.showTaskDetail(this.currentTaskId);
        }
    }

    /**
     * 启动任务
     */
    async startTask(taskId) {
        try {
            const response = await ApiService.startAnalysisTask(taskId);
            
            if (response.success) {
                NotificationService.success('任务启动成功');
                this.refreshTasks();
                if (this.currentTaskId === taskId) {
                    await this.refreshTaskDetail();
                }
            } else {
                NotificationService.error(response.message || '启动任务失败');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'start_task');
        }
    }

    /**
     * 停止任务
     */
    async stopTask(taskId) {
        try {
            const response = await ApiService.stopAnalysisTask(taskId);
            
            if (response.success) {
                NotificationService.success('任务停止成功');
                this.refreshTasks();
                if (this.currentTaskId === taskId) {
                    await this.refreshTaskDetail();
                }
            } else {
                NotificationService.error(response.message || '停止任务失败');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'stop_task');
        }
    }

    /**
     * 重试任务
     */
    async retryTask(taskId) {
        try {
            const response = await ApiService.retryAnalysisTask(taskId);
            
            if (response.success) {
                NotificationService.success('任务重试成功');
                this.refreshTasks();
                if (this.currentTaskId === taskId) {
                    await this.refreshTaskDetail();
                }
            } else {
                NotificationService.error(response.message || '重试任务失败');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'retry_task');
        }
    }

    /**
     * 删除任务
     */
    async deleteTask(taskId) {
        // 获取任务信息用于确认对话框
        const task = this.tasks.find(t => t.id === taskId);
        const taskName = task ? task.name : '此任务';
        
        // 使用更友好的确认对话框
        if (!this.showDeleteConfirmation(taskName)) {
            return;
        }

        try {
            console.log('正在删除任务:', taskId);
            
            // 禁用删除按钮，防止重复操作
            this.setTaskDeleteButtonState(taskId, true);
            
            const response = await ApiService.deleteAnalysisTask(taskId);
            console.log('删除任务响应:', response);
            
            if (response.success) {
                console.log('任务删除成功，显示成功通知');
                this.showDeleteSuccessNotification(taskName);
                
                // 延迟刷新任务列表，确保用户能看到反馈
                setTimeout(() => {
                    console.log('开始刷新任务列表');
                    this.refreshTasks();
                    
                    // 如果当前查看的任务是被删除的任务，关闭详情模态框
                    if (this.currentTaskId === taskId) {
                        console.log('关闭任务详情模态框');
                        this.closeTaskDetailModal();
                    }
                }, 800);
            } else {
                console.error('删除任务失败:', response.message);
                this.showDeleteErrorNotification(response.message || '删除任务失败');
            }
        } catch (error) {
            console.error('删除任务异常:', error);
            this.showDeleteErrorNotification('网络错误，请稍后重试');
        } finally {
            // 恢复删除按钮状态
            this.setTaskDeleteButtonState(taskId, false);
        }
    }

    /**
     * 显示删除确认对话框
     */
    showDeleteConfirmation(taskName) {
        return confirm(`确定要删除任务"${taskName}"吗？\n\n此操作不可恢复，请谨慎操作。`);
    }

    /**
     * 设置删除按钮状态
     */
    setTaskDeleteButtonState(taskId, disabled) {
        const deleteButtons = document.querySelectorAll(`button[onclick*="deleteTask(${taskId})"]`);
        deleteButtons.forEach(button => {
            button.disabled = disabled;
            if (disabled) {
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                button.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                button.innerHTML = '<i class="fas fa-trash"></i>';
                button.classList.remove('opacity-50', 'cursor-not-allowed');
            }
        });
    }

    /**
     * 显示删除成功通知
     */
    showDeleteSuccessNotification(taskName) {
        const message = `任务"${taskName}"删除成功`;
        
        if (window.NotificationService && window.NotificationService.success) {
            window.NotificationService.success(message);
        } else {
            // 回退方案：使用浏览器通知
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification('删除成功', {
                    body: message,
                    icon: '/static/images/success.png'
                });
            } else {
                // 最终回退：使用页面提示
                this.showPageNotification(message, 'success');
            }
        }
    }

    /**
     * 显示删除错误通知
     */
    showDeleteErrorNotification(errorMessage) {
        const message = `删除失败: ${errorMessage}`;
        
        if (window.NotificationService && window.NotificationService.error) {
            window.NotificationService.error(message);
        } else {
            // 回退方案：使用页面提示
            this.showPageNotification(message, 'error');
        }
    }

    /**
     * 显示页面通知
     */
    showPageNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full`;
        
        // 根据类型设置样式
        switch (type) {
            case 'success':
                notification.classList.add('bg-green-500', 'text-white');
                break;
            case 'error':
                notification.classList.add('bg-red-500', 'text-white');
                break;
            default:
                notification.classList.add('bg-blue-500', 'text-white');
        }
        
        notification.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-white hover:text-gray-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 显示动画
        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 300);
        }, 3000);
    }

    /**
     * 编辑任务
     */
    async editTask(taskId) {
        try {
            const response = await ApiService.getAnalysisTask(taskId);
            
            if (response.success) {
                this.populateEditForm(response.data);
                
                const modal = document.getElementById('editTaskModal');
                if (modal) {
                    modal.classList.remove('hidden');
                    modal.classList.add('flex');
                }
            } else {
                NotificationService.error(response.message || '获取任务信息失败');
            }
        } catch (error) {
            ErrorHandler.handleApiError(error, 'edit_task');
        }
    }

    /**
     * 填充编辑表单
     */
    populateEditForm(taskData) {
        if (!taskData || !taskData.task) {
            console.error('任务数据格式错误:', taskData);
            return;
        }

        const task = taskData.task;

        // 填充基本信息
        document.getElementById('editTaskId').value = task.id;
        document.getElementById('editTaskName').value = task.name || '';
        document.getElementById('editExecutionType').value = task.execution_type || '';
        document.getElementById('editMaxRetries').value = task.max_retries || 3;

        // 填充多选任务类型
        if (task.task_type) {
            // 先清空所有选择
            document.querySelectorAll('.edit-task-type-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });

            // 设置选中的任务类型
            const taskTypes = task.task_type.split(',').map(t => t.trim());
            taskTypes.forEach(type => {
                const checkbox = document.querySelector(`.edit-task-type-checkbox[value="${type}"]`);
                if (checkbox) {
                    checkbox.checked = true;
                }
            });
        }

        // 填充分析时段 - 处理日期格式
        if (task.analysis_start_date) {
            // 如果是ISO格式，转换为YYYY-MM-DD格式
            const startDate = new Date(task.analysis_start_date);
            if (!isNaN(startDate.getTime())) {
                const formattedDate = startDate.toISOString().split('T')[0];
                document.getElementById('editAnalysisStartDate').value = formattedDate;
            } else {
                // 如果已经是正确格式，直接使用
                document.getElementById('editAnalysisStartDate').value = task.analysis_start_date;
            }
        }
        if (task.analysis_end_date) {
            // 如果是ISO格式，转换为YYYY-MM-DD格式
            const endDate = new Date(task.analysis_end_date);
            if (!isNaN(endDate.getTime())) {
                const formattedDate = endDate.toISOString().split('T')[0];
                document.getElementById('editAnalysisEndDate').value = formattedDate;
            } else {
                // 如果已经是正确格式，直接使用
                document.getElementById('editAnalysisEndDate').value = task.analysis_end_date;
            }
        }

        // 填充数据源 - 需要确保数据源选项已加载
        if (task.data_source_id) {
            // 先加载数据源选项
            this.loadEditTaskDatasources().then(() => {
                // 数据源加载完成后设置值
                const dataSourceSelect = document.getElementById('editDataSource');
                if (dataSourceSelect) {
                    dataSourceSelect.value = task.data_source_id;
                    console.log(`设置编辑任务数据源: ${task.data_source_id}`);
                }
            }).catch(error => {
                console.error('加载编辑任务数据源失败:', error);
                // 如果加载失败，直接设置值（可能选项已存在）
                const dataSourceSelect = document.getElementById('editDataSource');
                if (dataSourceSelect) {
                    dataSourceSelect.value = task.data_source_id;
                }
            });
        } else {
            // 如果没有数据源ID，也要加载选项供用户选择
            this.loadEditTaskDatasources();
        }
    }

    /**
     * 加载编辑任务的数据源列表
     */
    async loadEditTaskDatasources() {
        try {
            console.log('开始加载编辑任务数据源列表...');

            // 检查是否已有数据源选项，避免重复加载
            const editDataSourceSelect = document.getElementById('editDataSource');
            if (!editDataSourceSelect) {
                console.warn('未找到编辑任务数据源选择框: editDataSource');
                return;
            }

            // 如果已经有选项（除了第一个），说明已加载过
            if (editDataSourceSelect.children.length > 1) {
                console.log('编辑任务数据源已加载，跳过重复加载');
                return;
            }

            const response = await ApiService.getDataSources();

            if (response.success) {
                console.log('编辑任务数据源加载成功:', response.data);
                // 处理不同的响应格式
                let datasources = [];
                if (Array.isArray(response.data)) {
                    datasources = response.data;
                } else if (response.data.datasources) {
                    datasources = response.data.datasources;
                } else if (response.data.items) {
                    datasources = response.data.items;
                }

                console.log('处理后的编辑任务数据源列表:', datasources);
                this.renderEditTaskDatasourceOptions(datasources);

                // 显示成功消息
                if (datasources && datasources.length > 0) {
                    console.log(`成功加载 ${datasources.length} 个编辑任务数据源`);
                }
            } else {
                console.error('编辑任务数据源加载失败:', response.message);
                // 尝试使用分析任务专用的数据源接口
                await this.loadEditTaskAnalysisDatasources();
            }
        } catch (error) {
            // 如果是401错误，说明用户未登录，这是正常的
            if (error.message && (error.message.includes('401') || error.message.includes('Not authenticated'))) {
                console.log('用户未登录，无法加载编辑任务数据源');
                return;
            }
            console.warn('通用数据源接口加载失败，尝试专用接口:', error);
            // 尝试使用分析任务专用的数据源接口
            await this.loadEditTaskAnalysisDatasources();
        }
    }

    /**
     * 加载编辑任务分析任务专用的数据源列表
     */
    async loadEditTaskAnalysisDatasources() {
        try {
            console.log('尝试加载编辑任务分析任务专用数据源列表...');
            const response = await ApiService.getAnalysisTaskDatasources();

            if (response.success) {
                console.log('编辑任务分析任务数据源加载成功:', response.data);
                let datasources = [];
                if (Array.isArray(response.data)) {
                    datasources = response.data;
                } else if (response.data.datasources) {
                    datasources = response.data.datasources;
                } else if (response.data.items) {
                    datasources = response.data.items;
                }

                console.log('处理后的编辑任务分析任务数据源列表:', datasources);
                this.renderEditTaskDatasourceOptions(datasources);

                // 显示成功消息
                if (datasources && datasources.length > 0) {
                    console.log(`成功加载 ${datasources.length} 个编辑任务数据源`);
                }
            } else {
                console.error('编辑任务分析任务数据源加载失败:', response.message);
                this.showEditTaskDatasourceError('加载数据源失败，请检查权限设置');
            }
        } catch (error) {
            console.error('编辑任务分析任务数据源加载异常:', error);
            this.showEditTaskDatasourceError('网络错误，请稍后重试');
        }
    }

    /**
     * 显示编辑任务数据源加载错误
     */
    showEditTaskDatasourceError(message) {
        const select = document.getElementById('editDataSource');
        if (select) {
            select.innerHTML = '<option value="">加载数据源失败</option>';
            select.disabled = true;
        }
        console.error('编辑任务数据源加载错误:', message);
    }

    /**
     * 渲染编辑任务数据源选项
     */
    renderEditTaskDatasourceOptions(datasources) {
        const select = document.getElementById('editDataSource');
        if (!select) {
            console.warn('未找到编辑任务数据源下拉框元素: editDataSource');
            return;
        }

        console.log('开始渲染编辑任务数据源选项，数据源数量:', datasources?.length || 0);

        // 清空现有选项，保留第一个选项
        while (select.children.length > 1) {
            select.removeChild(select.lastChild);
        }

        // 检查数据源数组
        if (!datasources || !Array.isArray(datasources) || datasources.length === 0) {
            console.log('没有可用的编辑任务数据源');
            const option = document.createElement('option');
            option.value = "";
            option.textContent = "暂无可用数据源";
            option.disabled = true;
            select.appendChild(option);
            select.disabled = true;
            return;
        }

        // 启用下拉框
        select.disabled = false;

        // 添加数据源选项
        let hasValidOptions = false;
        datasources.forEach((ds, index) => {
            console.log(`处理编辑任务数据源 ${index + 1}:`, ds);

            // 验证数据源对象
            if (!ds || !ds.id || !ds.name) {
                console.warn('跳过无效编辑任务数据源:', ds);
                return;
            }

            const option = document.createElement('option');
            option.value = ds.id;

            // 构建显示文本，包含更多有用信息
            let displayText = ds.name;

            // 添加类型信息
            if (ds.source_type) {
                displayText += ` [${ds.source_type}]`;
            }

            // 添加记录数量信息
            if (ds.record_count && ds.record_count > 0) {
                displayText += ` [${ds.record_count}条记录]`;
            }

            option.textContent = displayText;

            // 如果数据源状态不是active，禁用该选项
            if (ds.status !== 'active') {
                option.disabled = true;
                option.textContent += ' (不可用)';
            }

            select.appendChild(option);
            hasValidOptions = true;
        });

        console.log(`编辑任务数据源选项渲染完成，有效选项数量: ${hasValidOptions ? datasources.length : 0}`);

        // 如果没有有效的数据源选项，添加提示
        if (!hasValidOptions) {
            const option = document.createElement('option');
            option.value = "";
            option.textContent = "暂无可用数据源";
            option.disabled = true;
            select.appendChild(option);
            select.disabled = true;
        }
    }

    /**
     * 填充编辑服务配置
     */
    populateEditServices(services) {
        const container = document.getElementById('editServicesContainer');
        if (!container) return;
        
        // 清空现有配置
        container.innerHTML = '';
        
        if (!services || services.length === 0) {
            // 添加一个空的默认配置
            this.addEditServiceConfig();
            return;
        }
        
        // 添加每个服务配置
        services.forEach((service, index) => {
            const serviceHtml = this.createEditServiceHtml(service, index);
            container.insertAdjacentHTML('beforeend', serviceHtml);
        });
    }

    /**
     * 创建编辑服务配置HTML
     */
    createEditServiceHtml(service, index) {
        const serviceId = Date.now() + index;
        return `
            <div class="service-config border border-slate-200 rounded-lg p-4" data-service-id="${serviceId}">
                <div class="flex justify-between items-start mb-3">
                    <h4 class="font-medium text-slate-800">服务配置 ${index + 1}</h4>
                    <div class="flex items-center space-x-2">
                        <div class="flex items-center">
                            <input type="checkbox" class="service-enable mr-2" ${service.status !== 'disabled' ? 'checked' : ''}>
                            <label class="text-sm text-slate-600">启用</label>
                        </div>
                        <button type="button" onclick="analysisManager.removeEditServiceConfig(${serviceId})" 
                                class="text-red-600 hover:text-red-800">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务名称</label>
                        <input type="text" class="service-name w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="${this.escapeHtml(service.name || service.service_name || '')}" placeholder="请输入服务名称">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务类型</label>
                        <select class="service-type w-full px-3 py-1 text-sm border border-slate-300 rounded">
                            <option value="information_extraction" ${service.type === 'information_extraction' || service.service_type === 'information_extraction' ? 'selected' : ''}>信息提取</option>
                            <option value="pollution_type_recognition" ${service.type === 'pollution_type_recognition' || service.service_type === 'pollution_type_recognition' ? 'selected' : ''}>污染类型识别</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">批次大小</label>
                        <input type="number" class="batch-size w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="${service.parameters?.batch_size || 10}" min="1" max="100">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">并发数</label>
                        <input type="number" class="concurrency w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="${service.parameters?.concurrency || 5}" min="1" max="20">
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 添加编辑服务配置
     */
    addEditServiceConfig() {
        const container = document.getElementById('editServicesContainer');
        if (!container) return;

        const serviceId = Date.now();
        const serviceHtml = `
            <div class="service-config border border-slate-200 rounded-lg p-4" data-service-id="${serviceId}">
                <div class="flex justify-between items-start mb-3">
                    <h4 class="font-medium text-slate-800">新服务配置</h4>
                    <div class="flex items-center space-x-2">
                        <div class="flex items-center">
                            <input type="checkbox" class="service-enable mr-2" checked>
                            <label class="text-sm text-slate-600">启用</label>
                        </div>
                        <button type="button" onclick="analysisManager.removeEditServiceConfig(${serviceId})" 
                                class="text-red-600 hover:text-red-800">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务名称</label>
                        <input type="text" class="service-name w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="新服务" placeholder="请输入服务名称">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">服务类型</label>
                        <select class="service-type w-full px-3 py-1 text-sm border border-slate-300 rounded">
                            <option value="information_extraction">信息提取</option>
                            <option value="pollution_type_recognition">污染类型识别</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">批次大小</label>
                        <input type="number" class="batch-size w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="10" min="1" max="100">
                    </div>
                    <div>
                        <label class="block text-sm text-slate-600 mb-1">并发数</label>
                        <input type="number" class="concurrency w-full px-3 py-1 text-sm border border-slate-300 rounded" 
                               value="5" min="1" max="20">
                    </div>
                </div>
            </div>
        `;

        container.insertAdjacentHTML('beforeend', serviceHtml);
    }

    /**
     * 移除编辑服务配置
     */
    removeEditServiceConfig(serviceId) {
        const serviceConfig = document.querySelector(`#editServicesContainer [data-service-id="${serviceId}"]`);
        if (serviceConfig) {
            serviceConfig.remove();
        }
    }

    /**
     * 关闭编辑任务模态框
     */
    closeEditTaskModal() {
        const modal = document.getElementById('editTaskModal');
        if (modal) {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            this.resetEditTaskForm();
        }
    }

    /**
     * 重置编辑任务表单
     */
    resetEditTaskForm() {
        const form = document.getElementById('editTaskForm');
        if (form) {
            form.reset();
        }
        
        // 重置服务配置
        const container = document.getElementById('editServicesContainer');
        if (container) {
            container.innerHTML = '';
        }
    }

    /**
     * 保存编辑的任务
     */
    async saveEditTask() {
        try {
            const saveBtn = document.getElementById('saveEditTaskBtn');
            if (!saveBtn) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('保存按钮未找到');
                }
                console.error('saveEditTask: saveEditTaskBtn element not found');
                return;
            }
            
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>保存中...';
            saveBtn.disabled = true;

            const taskIdInput = document.getElementById('editTaskId');
            if (!taskIdInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('任务ID输入框未找到');
                }
                console.error('saveEditTask: editTaskId element not found');
                return;
            }
            
            const taskId = parseInt(taskIdInput.value);
            if (!taskId || isNaN(taskId)) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('任务ID无效');
                }
                return;
            }
            
            const taskData = this.collectEditTaskData();
            if (!taskData) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('表单数据不完整，请检查输入');
                }
                return;
            }
            
            const response = await ApiService.updateAnalysisTask(taskId, taskData);
            
            if (response.success) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.success('任务更新成功');
                }
                this.closeEditTaskModal();
                this.refreshTasks();
                if (this.currentTaskId === taskId) {
                    await this.refreshTaskDetail();
                }
            } else {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error(response.message || '更新任务失败');
                }
            }
        } catch (error) {
            console.error('saveEditTask error:', error);
            if (typeof ErrorHandler !== 'undefined') {
                ErrorHandler.handleApiError(error, 'save_edit_task');
            } else if (typeof NotificationService !== 'undefined') {
                NotificationService.error('更新任务时发生错误');
            }
        } finally {
            const saveBtn = document.getElementById('saveEditTaskBtn');
            if (saveBtn) {
                saveBtn.innerHTML = '<i class="fas fa-save mr-2"></i>保存修改';
                saveBtn.disabled = false;
            }
        }
    }

    /**
     * 收集编辑任务表单数据
     */
    collectEditTaskData() {
        try {
            // 表单验证
            const taskNameInput = document.getElementById('editTaskName');
            if (!taskNameInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('任务名称输入框未找到');
                }
                console.error('collectEditTaskData: editTaskName element not found');
                return null;
            }
            
            const taskName = taskNameInput.value.trim();
            if (!taskName) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请输入任务名称');
                }
                return null;
            }

            // 验证至少选择一个任务类型
            const taskTypes = [];
            const taskTypeCheckboxes = document.querySelectorAll('.edit-task-type-checkbox:checked');
            if (taskTypeCheckboxes.length === 0) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请至少选择一个任务类型');
                }
                return null;
            }
            
            taskTypeCheckboxes.forEach(checkbox => {
                taskTypes.push(checkbox.value);
            });
            
            const taskTypeString = taskTypes.join(',');

            // 验证数据源
            const dataSourceInput = document.getElementById('editDataSource');
            if (!dataSourceInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('数据源选择框未找到');
                }
                console.error('collectEditTaskData: editDataSource element not found');
                return null;
            }
            
            const dataSourceId = dataSourceInput.value;
            if (!dataSourceId) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请选择数据源');
                }
                return null;
            }

            // 验证分析时段（如果提供了结束日期，则开始日期必须存在）
            const analysisStartDateInput = document.getElementById('editAnalysisStartDate');
            const analysisEndDateInput = document.getElementById('editAnalysisEndDate');
            
            if (!analysisStartDateInput || !analysisEndDateInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('分析时段输入框未找到');
                }
                console.error('collectEditTaskData: edit analysis date elements not found');
                return null;
            }
            
            const analysisStartDate = analysisStartDateInput.value;
            const analysisEndDate = analysisEndDateInput.value;
            
            if (analysisEndDate && !analysisStartDate) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('请选择分析开始日期');
                }
                return null;
            }

            // 获取其他必填字段
            const executionTypeInput = document.getElementById('editExecutionType');
            const maxRetriesInput = document.getElementById('editMaxRetries');
            
            if (!executionTypeInput || !maxRetriesInput) {
                if (typeof NotificationService !== 'undefined') {
                    NotificationService.error('执行方式或重试次数输入框未找到');
                }
                console.error('collectEditTaskData: edit executionType or maxRetries element not found');
                return null;
            }

            return {
                name: taskName,
                task_type: taskTypeString,
                execution_type: executionTypeInput.value,
                data_source_id: parseInt(dataSourceId),
                analysis_start_date: analysisStartDate || null,
                analysis_end_date: analysisEndDate || null,
                services: [], // 移除服务配置
                max_retries: parseInt(maxRetriesInput.value) || 3,
                priority: 'medium', // 添加默认优先级
                config: {} // 简化配置
            };
        } catch (error) {
            console.error('collectEditTaskData error:', error);
            if (typeof NotificationService !== 'undefined') {
                NotificationService.error('收集编辑表单数据时发生错误');
            }
            return null;
        }
    }

    /**
     * 处理模态框点击事件
     */
    handleModalClick(e) {
        if (e.target.classList.contains('modal')) {
            const modalId = e.target.id;
            const modalActions = {
                'addAnalysisModal': () => this.closeAddTaskModal(),
                'taskDetailModal': () => this.closeTaskDetailModal(),
                'editTaskModal': () => this.closeEditTaskModal()
            };
            
            if (modalActions[modalId]) {
                modalActions[modalId]();
            }
        }
    }

    /**
     * 关闭所有模态框
     */
    closeAllModals() {
        this.closeAddTaskModal();
        this.closeTaskDetailModal();
        this.closeEditTaskModal();
    }

    /**
     * 启动自动刷新
     */
    startAutoRefresh() {
        if (this.refreshInterval) {
            console.log('自动刷新已经在运行中');
            return;
        }
        
        console.log(`启动自动刷新，间隔: ${this.refreshIntervalTime}ms`);
        this.refreshInterval = setInterval(() => {
            if (this.isAutoRefreshEnabled && this.hasRunningTasks()) {
                this.debouncedRefresh();
            }
        }, this.refreshIntervalTime);
    }

    /**
     * 停止自动刷新
     */
    stopAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
        }
    }

    /**
     * 防抖刷新方法
     */
    debouncedRefresh() {
        // 清除之前的防抖定时器
        if (this.debounceTimer) {
            clearTimeout(this.debounceTimer);
        }
        
        // 检查最小请求间隔
        const now = Date.now();
        if (now - this.lastRequestTime < this.minRequestInterval) {
            console.log('请求过于频繁，跳过此次刷新');
            return;
        }
        
        // 设置防抖延迟
        this.debounceTimer = setTimeout(() => {
            this.refreshTasks();
            if (this.currentTaskId) {
                this.refreshTaskDetail();
            }
            this.lastRequestTime = Date.now();
            this.requestCount++;
        }, 500); // 500ms防抖延迟
    }

    /**
     * 检查是否有运行中的任务
     */
    hasRunningTasks() {
        return this.tasks.some(task => task.status === 'running');
    }

    /**
     * 处理请求成功
     */
    handleRequestSuccess() {
        this.errorCount = 0; // 重置错误计数
        if (!this.isAutoRefreshEnabled) {
            this.isAutoRefreshEnabled = true;
            console.log('恢复自动刷新');
            this.updateRefreshStatusUI();
        }
        this.updateStatsUI();
    }

    /**
     * 处理请求错误
     */
    handleRequestError() {
        this.errorCount++;
        console.log(`请求错误计数: ${this.errorCount}/${this.maxErrors}`);
        this.updateStatsUI();
        
        if (this.errorCount >= this.maxErrors) {
            console.log('错误次数过多，暂停自动刷新');
            this.pauseAutoRefresh();
            
            // 30秒后尝试恢复
            setTimeout(() => {
                console.log('尝试恢复自动刷新');
                this.errorCount = 0;
                this.resumeAutoRefresh();
            }, 30000);
        }
    }

    /**
     * 暂停自动刷新
     */
    pauseAutoRefresh() {
        this.isAutoRefreshEnabled = false;
        console.log('自动刷新已暂停');
    }

    /**
     * 恢复自动刷新
     */
    resumeAutoRefresh() {
        if (this.errorCount < this.maxErrors) {
            this.isAutoRefreshEnabled = true;
            console.log('自动刷新已恢复');
        }
    }

    /**
     * 手动刷新
     */
    manualRefresh() {
        console.log('执行手动刷新');
        this.lastRequestTime = Date.now();
        this.refreshTasks();
        if (this.currentTaskId) {
            this.refreshTaskDetail();
        }
    }

    /**
     * 切换自动刷新状态
     */
    toggleAutoRefresh() {
        this.isAutoRefreshEnabled = !this.isAutoRefreshEnabled;
        this.updateRefreshStatusUI();
        
        if (this.isAutoRefreshEnabled) {
            console.log('启用自动刷新');
            // 重置错误计数
            this.errorCount = 0;
        } else {
            console.log('禁用自动刷新');
        }
    }

    /**
     * 更新刷新状态UI
     */
    updateRefreshStatusUI() {
        const statusElement = document.getElementById('refreshStatus');
        const toggleButton = document.getElementById('autoRefreshToggle');
        const requestInfoElement = document.getElementById('requestInfo');
        const errorInfoElement = document.getElementById('errorInfo');
        
        if (statusElement) {
            statusElement.textContent = this.isAutoRefreshEnabled ? '自动刷新已启用' : '自动刷新已暂停';
        }
        
        if (toggleButton) {
            const icon = toggleButton.querySelector('i');
            const text = toggleButton.childNodes[toggleButton.childNodes.length - 1];
            
            if (this.isAutoRefreshEnabled) {
                icon.className = 'fas fa-pause mr-2';
                text.textContent = '暂停自动刷新';
                toggleButton.classList.remove('bg-green-600', 'text-white');
                toggleButton.classList.add('border', 'border-slate-300', 'text-slate-700');
            } else {
                icon.className = 'fas fa-play mr-2';
                text.textContent = '启用自动刷新';
                toggleButton.classList.add('bg-green-600', 'text-white');
                toggleButton.classList.remove('border', 'border-slate-300', 'text-slate-700');
            }
        }
        
        if (requestInfoElement) {
            requestInfoElement.textContent = `请求计数: ${this.requestCount}`;
        }
        
        if (errorInfoElement) {
            errorInfoElement.textContent = `错误计数: ${this.errorCount}`;
        }
    }

    /**
     * 更新统计信息（扩展版本）
     */
    updateStatsUI() {
        this.updateRefreshStatusUI();
        // 这里可以添加其他统计信息的更新
    }

    /**
     * 格式化日期
     */
    formatDate(dateString) {
        if (!dateString) return '';
        return new Date(dateString).toLocaleString('zh-CN');
    }

    /**
     * 格式化时长
     */
    formatDuration(seconds) {
        if (!seconds) return '-';
        
        if (seconds < 60) {
            return `${seconds.toFixed(1)}秒`;
        } else if (seconds < 3600) {
            return `${(seconds / 60).toFixed(1)}分钟`;
        } else {
            return `${(seconds / 3600).toFixed(1)}小时`;
        }
    }

    /**
     * HTML转义，防止XSS攻击
     */
    escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * 销毁管理器
     */
    destroy() {
        this.stopAutoRefresh();
        this.closeAllModals();
    }
}

// 导出为全局类
window.AnalysisManager = AnalysisManager;